﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Manazra.Helpers;

namespace Manazra.Models.Repository
{
    public class CommentRepository
    {
        //data context
        private ManazraDataContext dc = new ManazraDataContext();

        //returns a parent segment by id
        public ArticleSegment GetParent(int id)
        {
            return dc.ArticleSegments.SingleOrDefault(r => r.RecId == id);
        }

        //returns a comment by id
        public Comment GetById(int id)
        {
            return dc.Comments.SingleOrDefault(c => c.RecId == id);
        }

        //adds a new comment
        public void Add(Comment comment)
        {
            dc.Comments.InsertOnSubmit(comment);
        }

        //returns comment types
        public IQueryable<String> GetTypes()
        {
            return from ct in dc.CommentTypes
                   where ct.Type != "N/A"
                   select ct.Type;
        }

        //returns a response type by id
        public CommentType GetTypeByName(string name)
        {
            return dc.CommentTypes.SingleOrDefault(r => r.Type == name);
        }

        //deletes a comment
        public void Delete(Comment comment)
        {
            //first delete points for all replies on this comment
            int points = comment.Replies.Count() * (int)RankPoints.Reply;
            comment.ArticleSegment.Article.Points -= points;

            //first delete all replies for this comment
            dc.Replies.DeleteAllOnSubmit(comment.Replies);
            //now we can delete the comment
            dc.Comments.DeleteOnSubmit(comment);
        }

        //add points to article - for comment
        public void AddPoints(Comment comment)
        {
            comment.ArticleSegment.Article.Points += (int)RankPoints.Comment;
        }

        //delete points from article - for this comment
        public void DelPoints(Comment comment)
        {
            comment.ArticleSegment.Article.Points -= (int)RankPoints.Comment;
        }

        //save
        public void Save()
        {
            dc.SubmitChanges();
        }
    }
}
